from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import users
from mako.template import Template
from mako.lookup import TemplateLookup

from models.project import MasterControlProject, MasterControlSubProject
from utilities import GetToken, GetProject
import random, sys


class AddProjectHandler(webapp.RequestHandler):
    def get(self):
        return self.__view('', '', '', '')
        
    def post(self):
        token = self.request.POST.get('token', '')
        username = self.request.POST.get('pivotal_username', '')
        password = self.request.POST.get('pivotal_password', '')
        project_id = self.request.POST.get('project_id', '')
        
        errors = []
        if not token and username and password:
            token = GetToken(username, password)
            username = ''
            password = ''
        if not token:
            errors.append('Token or username and password must be supplied.')
            
        if not project_id:
            errors.append('Pivotal Project ID must be supplied.')
        else:
            try:
                project_id = int(project_id)
            except:
                errors.append('Pivotal Project ID must be an integer.')
        
        if errors:
            return self.__view(errors, project_id or '', token, username)
        
        project = GetProject(project_id, token)
        if project:
            name = project.getElementsByTagName('name')[0].firstChild.data.strip()
        else:
            errors.append('User associated with token does not have access to project %s' % (project_id, ))
            return self.__view(errors, project_id, token, username)
            
        try:
            if MasterControlProject.all().filter('pivotal_project_id =', project_id).get() or MasterControlSubProject.all().filter('pivotal_project_id =', project_id).get():
                errors.append('Cannot create a MasterControl project with Pivotal Project ID %d as it is already used in MasterControl' % (project_id, ))
                return self.__view(errors, project_id, token, username)
            
            key = hex(random.randint(1000000000, sys.maxint))[2:]
            mcp = MasterControlProject(key_name = key, pivotal_project_id = int(project_id), name = name, token = token)
            mcp.put()
            self.redirect('/secure/')
            return
        except:
            errors.append('Unable to add project.')
            return self.__view(errors, project_id or '', token, username)
    
    def __view(self, errors, project_id, token, username):
        temp = Template(filename = 'templates/add_project.html', lookup = TemplateLookup(directories=['.']))
        self.response.out.write(temp.render(errors = errors, project_id = project_id, token = token, username = username))